package com.example.administrator.slidedemo;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class SlideAdapter extends BaseAdapter implements SlideView.OnSlideListener {

	private Context mContext;
	private LayoutInflater mInflater;

	private List<MessageBean> mMessageItems = new ArrayList<MessageBean>();
	private SlideView mLastSlideViewWithStatusOn;

	SlideAdapter(Context context, List<MessageBean> messageItems) {
		mMessageItems = messageItems;
		mContext = context;
		mInflater = LayoutInflater.from(mContext);
	}


	@Override
	public int getCount() {
		if (mMessageItems == null) {
			mMessageItems = new ArrayList<MessageBean>();
		}
		return mMessageItems.size();
	}

	@Override
	public Object getItem(int position) {
		return mMessageItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	/**
	 * 这个方法重要
	 * @param position
	 * @param convertView
	 * @param parent
     * @return
     */
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		SlideView slideView = (SlideView) convertView;
		if (slideView == null) {
			View itemView = mInflater.inflate(R.layout.items_text,
					null);

			slideView = new SlideView(mContext);
			slideView.setContentView(itemView);
			holder = new ViewHolder(slideView);
			slideView.setOnSlideListener(this);
			slideView.setTag(holder);
		} else {
			holder = (ViewHolder) slideView.getTag();
		}
		MessageBean item = mMessageItems.get(position);
		item.slideView = slideView;
		item.slideView.shrink();
		holder.title.setText(item.getTitle());
		holder.deleteHolder.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mMessageItems.remove(position);
				notifyDataSetChanged();
			}
		});

		return slideView;
	}

	private static class ViewHolder {
		public TextView title;
		public ViewGroup deleteHolder;

		ViewHolder(View view) {
			title = (TextView) view.findViewById(R.id.tv_lv);//listview 里面的item
			deleteHolder = (ViewGroup) view.findViewById(R.id.holder);//删除按钮
		}
	}

	@Override
	public void onSlide(View view, int status) {
		if (mLastSlideViewWithStatusOn != null
				&& mLastSlideViewWithStatusOn != view) {
			mLastSlideViewWithStatusOn.shrink();
		}

		if (status == SLIDE_STATUS_ON) {
			mLastSlideViewWithStatusOn = (SlideView) view;
		}
	}
}
